package imwallet.dichen.com.library.utils;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;

import java.io.File;
import java.io.IOException;

/**
 * 照片选择器
 *
 * @author Administrator
 * @date 2018/6/11
 */

public class PictureSelector {
    private static PictureSelector sInstance;

    public static PictureSelector get() {
        if(sInstance == null) {
            synchronized (PictureSelector.class) {
                if(sInstance == null) {
                    sInstance = new PictureSelector();
                }
            }
        }
        return sInstance;
    }

    /**
     * 打开照相机
     */
    public void openCamear(Activity activity, int requestCode) {
        Intent intent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        // 打开手机相册,设置请求码
        activity.startActivityForResult(intent, requestCode);
    }

    /**
     * 打开相册
     */
    private void openGallery(Activity activity, int requestCode) {
        Intent intent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // 打开手机相册,设置请求码
        activity.startActivityForResult(intent, requestCode);
    }

    /**
     * 裁剪图片
     *
     * @param uri
     */
    public void cropImage(Activity activity, Uri uri, String path, int requestCode) {
        if(uri == null) {
            return;
        }
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("scale", true);
        // 裁剪比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        File outFile;
        Uri outUri;
        if(!TextUtils.isEmpty(path)) {
            outFile = new File(path, "temp.jpg");
            if(outFile.exists()) {
                outFile.delete();
            }
            try {
                outFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 文件输出位置
            outUri = Uri.fromFile(outFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outUri);
        }
        activity.startActivityForResult(intent, requestCode);
    }
}
